package com.cqupt.slewing

import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.util.AttributeSet
import android.util.Log
import android.view.View
import androidx.core.content.ContextCompat
import androidx.core.graphics.drawable.toBitmap
import androidx.core.graphics.withTranslation
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent
import kotlinx.coroutines.*
import okhttp3.OkHttpClient
import okhttp3.Request
import org.json.JSONObject


class MyView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr), LifecycleObserver {

    private var locatingJob: Job? = null
    private val locateBitmap: Bitmap? =
        ContextCompat.getDrawable(context, R.drawable.ic_item)?.toBitmap(100, 100)

    var macID = ""

    // 定位失物坐标
    private var locateX = 0f
    private var locateY = 0f

    // 保存画布的宽和高
    private var mWidth = 0f
    private var mHeight = 0f

    constructor(context: Context, macID: String) : this(context) {
        this.macID = macID
    }
    // 初始化画笔
//    private val paint = Paint().apply {
//        style = Paint.Style.STROKE
//        strokeWidth = 50f
//        color = ContextCompat.getColor(context, R.color.yellow_ffe27b)
//    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        mWidth = w.toFloat()
        mHeight = h.toFloat()
    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        canvas?.also {
            drawLocation(it)
        }

    }

    private fun drawLocation(canvas: Canvas) {
        canvas.withTranslation(0f, mHeight) {

//            drawLine(-mWidth/2,0f,mWidth/2,0f,paint)
            locateBitmap?.let {
                drawBitmap(
                    it,
                    (locateX * mWidth * 0.64f / 8f - 50) + mWidth * 0.36f,
                    -(locateY * mHeight / 7.4f + 100),
                    null
                )
            }
        }
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    fun startLocate() {
        locatingJob = CoroutineScope(Dispatchers.Main).launch {
            while (true) {
                delay(1000)
                if (macID.isNotBlank()) {
                    val location = updateLocation("device/get_location/$macID")
                    invalidate()    // 刷新view
                }
            }
        }
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    fun pauseLocate() {
        locatingJob?.cancel()
    }

    private suspend fun updateLocation(urlString: String): List<Float> {
        val data = arrayListOf<Float>()
        val client = OkHttpClient()
        val request: Request = Request.Builder()
            .url(MyRepository.HOST + urlString)
            .build()

        withContext(Dispatchers.IO) {
            val response = client.newCall(request).execute()
            val json = JSONObject(response.body?.string())
            locateX = json.getDouble("x").toFloat()
            locateY = json.getDouble("y").toFloat()
            Log.d("myTAG", "x: $locateX, y: $locateY")
        }
        return data
    }
}